package top.soulblack.purchasesale.controller.setting;

import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.soulblack.purchasesale.common.Result;
import top.soulblack.purchasesale.mapper.RoleMapper;
import top.soulblack.purchasesale.model.Role;
import top.soulblack.purchasesale.model.User;
import top.soulblack.purchasesale.service.RoleService;
import static top.soulblack.purchasesale.common.CodeMsg.*;
import top.soulblack.purchasesale.service.UserService;

import javax.xml.crypto.Data;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/staff")
public class StaffCorntroller {
    @Autowired
    private UserService staffService;

    @Autowired
    private RoleMapper roleMapper;

    @RequestMapping("/addStaff")
    @ResponseBody
    public Result<Boolean> addCorlor(User staff) {
        // 判断是否存在当前颜色
        if (staffService.existUser(staff.getAccount())) {
            return Result.error(STAFF_EXIST);
        }
        // 判断排序数是否在1到100区间
        if (staff.getSort() > 100 || staff.getSort() < 1) {
            return Result.error(SORT_ERROR);
        }
        staffService.addUser(staff);
        return Result.success(true);
    }

    @RequestMapping("/deletestaff")
    @ResponseBody
    // 后期需要加上User权限验证，否则暴露接口有危险。
    public Result<Boolean> deletestaff(Integer staffId) {
        if (staffService.deleteUser(staffId)) {
            return Result.success(true);
        }
        return Result.error(STAFF_DELETE);
    }

    @RequestMapping("/saveStaff")
    @ResponseBody
    public Result<Boolean> saveStaff(String oldaccount,User staff) {
        if(oldaccount==""){
            if (staffService.existUser(staff.getAccount())) {
                return Result.error(ROlE_EXIST);
            }
            Date mod=new Date();
            SimpleDateFormat now=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            staff.setCreatime(now.format(mod));
            staff.setLoadtime(now.format(mod));
            //User use=new User();
            //BeanUtils.copyProperties(staff,use);
            if(staffService.addUser(staff))
                return Result.success(true);
            else
                Result.error(STAFF_ERROR);
        }
        boolean flag=oldaccount.equals(staff.getAccount());
        if (staffService.existUser(staff.getAccount())&&(!oldaccount.equals(staff.getAccount()))) {
            return Result.error(STAFF_ERROR);
        }
        staffService.updateUser(staff);
        return Result.success(true);
    }
}
